package com.supersit.greensproject.AsyncTask;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.supersit.greensproject.R;
import com.supersit.greensproject.entity.BaseBase;
import com.supersit.greensproject.entity.MaketSubject;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/25 0025.
 */
public class UpdateBaseListAndMaketList {
    private int[] baseAuthority;
    private int[] maketAuthority;
    private ShowDialog showDialog;
    private List<BaseBase> updateBaseList;
    private List<MaketSubject> updateMaketList;
    private DbManager dbManager;
    private final int UPDATE_SUCCESS = 111;
    private final int UPDATE_FAIL = 222;
    private final int SERVICE_ERROR = 333;
    private final int NOUPDATE = 444;
    private final int SERVICE_DATA_ERROR = 555;
    private boolean isUpdateBaseData = false;
    private Context context;

    public UpdateBaseListAndMaketList(int[] baseAuthority, int[] maketAuthority, Context context) {
        this.context = context;
        this.baseAuthority = baseAuthority;
        this.maketAuthority = maketAuthority;
        showDialog = new ShowDialog(context);
    }

    /**
     * 从服务器更新主体基地数据
     */
    public void updateBaseData() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < baseAuthority.length; i++) {
            if (i == baseAuthority.length - 1) {
                sb.append(baseAuthority[i] + "");
            } else {
                sb.append(baseAuthority[i] + ",");
            }
        }
//        BaseBase bb = null;
//        try {
//        bb = dbManager.selector(BaseBase.class).orderBy("timeStamp", false).limit()
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
        long time = 0;
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/data/data/com.supersit.greensproject/databases/greens.db", null);
        Cursor cursor = db.rawQuery("select timeStamp from base order by timeStamp desc limit 1", null);
        if (cursor.moveToFirst()) {
            time = cursor.getLong(cursor.getColumnIndex("timeStamp"));
        }
        db.close();

//
//        long time = 0;
//        if (null != bb)
//            time = bb.getTimeStamp();
        L.d("手机的时间戳：" + time);
        Map<String, String> map = new HashMap<>();
        map.put("type", sb.toString());
        map.put("newTime", time == 0 ? "" : String.valueOf(time));
        String url = API.selectProductionBaseList;
        showDialog.showLoadingDialog(context.getString(R.string.loading));
        HttpXUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                L.e("select base synchorization result error", ex.getMessage());
                if (maketAuthority.length > 0) {//更新基地数据时，接口异常，如有市场权限，更新市场数据
                    T.showShort(context, R.string.base_data_error);
                    updateMaketData();
                } else {//服务器异常
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                L.d("update base  result", result);
                updateBaseList = new ArrayList<>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int isfalse = jsonObject.optInt("isfalse");
                    String msg = jsonObject.optString("msg");
                    if (isfalse == 1) {//1成功 0失敗
                        JSONArray jsonArray = jsonObject.optJSONArray("resultdata");
                        if (jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.optJSONObject(i);
                                String objectid = item.optString("objectid");
                                int baseId = item.optInt("id");
                                String jdnum = item.optString("jdnum");//基地编号
                                String baseName = item.optString("name");
                                String businessLicence = item.optString("no");//许可证
                                String address = item.optString("address");//地址
                                String productCategory = item.optString("productCategory");//pc用，android无用。
                                String area = item.optString("area");//pc用，android无用。
                                String type = item.optString("type");//基础类型中文字符串 pc用，android无用。
                                String contacts = item.optString("conname");//联系人
                                String tel = item.optString("tel");
                                String email = item.optString("email");
                                int flag = item.optInt("flag");//用地规划用的。现在无用
                                String cteatetime = item.optString("createtime");//上报基地时间 无用
                                int isDelete = item.optInt("isdelete");
                                int operstatus = item.optInt("operstatus");//操作状态  0删除 1新增 2修改
                                long timestamp = item.optLong("timestamp");//时间戳
                                String output = item.optString("output");//产量
                                int productTypeId = item.optInt("cid");//基地类型ID 0蔬菜 1肉鸡 2奶牛 3渔业 4生猪
                                int areaId = item.optInt("aid");//所在区的ID
                                String areaName = item.optString("areaName");//所在区的名称
                                String shape = item.optString("shape");//无用
                                String proportion = item.optString("areaSize");//面积;
                                String latitudes = item.optString("latitude");
                                String longitude = item.optString("longitude");
                                BaseBase bb = new BaseBase();
                                bb.setBaseId(baseId);
                                bb.setBaseName(baseName);
                                bb.setBaseAddress(address);
                                bb.setAreaId(areaId);
                                bb.setProductTypeId(productTypeId);
                                bb.setContacts(contacts);
                                bb.setTel(tel);
                                bb.setEmail(email);
                                bb.setProportion(proportion);
                                bb.setOutPut(output);
                                bb.setQuarter("");//季度
                                bb.setExpectedDate("");
                                bb.setExpectedOutPut("");
                                bb.setTheeirAbility("");
                                bb.setType(productTypeId);
                                bb.setFlag(flag + "");
                                bb.setCreateDate(cteatetime);//上报时间
                                bb.setTimeStamp(timestamp);
                                bb.setOperationsTatus(operstatus);
                                bb.setLatitudes(latitudes);
                                bb.setLongitudes(longitude);
                                bb.setBusinessLicence(businessLicence);
                                bb.setIsDelete(isDelete);
                                updateBaseList.add(bb);
                            }
                            if (maketAuthority.length > 0) {//如果有市场权限，就更新市场数据
                                isUpdateBaseData = true;
                                updateMaketData();
                            } else {//从服务器获取数据完成，更新数据库
                                Message message = new Message();
                                message.what = UPDATE_SUCCESS;
                                handler.sendMessage(message);
                            }
                        } else {//基地无需更新，更新市场
                            if (maketAuthority.length > 0) {//如果有市场权限，就更新市场数据
                                updateMaketData();
                            } else {//当前数据已经是最新的数据
                                Message message = new Message();
                                message.what = NOUPDATE;
                                handler.sendMessage(message);
                            }
                        }

                    } else {//更新基地信息时服务器数据异常
                        if (maketAuthority.length > 0) {//如果有市场权限，更新市场数据
                            T.showShort(context, R.string.base_data_error);
                            updateMaketData();
                        } else {//服务器数据异常
                            Message message = new Message();
                            message.what = SERVICE_DATA_ERROR;
                            handler.sendMessage(message);
                        }
                    }
                } catch (JSONException e) {
                    if (maketAuthority.length > 0) {//JSON数据异常，如果有市场权限，更新市场数据
                        T.showShort(context, R.string.base_data_error);
                        updateMaketData();
                    } else {//更新基地信息时服务器数据异常
                        Message message = new Message();
                        message.what = SERVICE_DATA_ERROR;
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    /**
     * 从服务器更新市主体数据
     */

    private void updateMaketData() {
        showDialog.dismissLoadDialog();
        MaketSubject ms = null;
//        try {
//            ms = dbManager.selector(MaketSubject.class).orderBy("timeStamp", false).findFirst();
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//        long time = 0;
//        if (null != ms)
//            time = ms.getTimeStamp();
        long time = 0;
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/data/data/com.supersit.greensproject/databases/greens.db", null);
        Cursor cursor = db.rawQuery("select timeStamp from maket order by timeStamp desc limit 1", null);
        if (cursor.moveToFirst()) {
            time = cursor.getLong(cursor.getColumnIndex("timeStamp"));
        }
        db.close();

        Map<String, String> map = new HashMap<>();
        map.put("newTime", time == 0 ? "" : String.valueOf(time));
        String url = API.selectMarketList;
        showDialog.showLoadingDialog(context.getString(R.string.loading));
        HttpXUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                L.e("select base synchorization result error", ex.getMessage());
                if (isUpdateBaseData) {
                    T.showShort(context, R.string.maket_data_error);
                    Message message = new Message();
                    message.what = UPDATE_SUCCESS;
                    handler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                }

            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                L.d("select base synchorization result", result);
                updateMaketList = new ArrayList<>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int isfalse = jsonObject.optInt("isfalse");
                    String msg = jsonObject.optString("msg");
                    if (isfalse == 1) {//1成功 0失敗
                        JSONArray jsonArray = jsonObject.optJSONArray("resultdata");
                        if (jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.optJSONObject(i);
                                int maketId = item.optInt("mark_id") == 0 ? 0 : item.optInt("mark_id");
                                int areaId = item.optInt("aid") == 0 ? 0 : item.optInt("aid");//所在的区
                                String maketName = TextUtils.isEmpty(item.optString("marketname")) ? "" : item.optString("marketname").trim();
                                String operator = TextUtils.isEmpty(item.optString("operator")) ? "" : item.optString("operator").trim();//经营者
                                String tel = TextUtils.isEmpty(item.optString("tel")) ? "" : item.optString("tel").trim();
                                String maketAddress = TextUtils.isEmpty(item.optString("marketaddr")) ? "" : item.optString("marketaddr").trim();
                                int category = item.optInt("category");//市场类型 0批发市场  1零售市场
                                String maketBy = TextUtils.isEmpty(item.optString("marketdecs")) ? "" : item.optString("marketdecs").trim();//市场说明
                                String createDate = TextUtils.isEmpty(item.optString("createtime")) ? "" : item.optString("createtime").trim();
                                String latitudes = TextUtils.isEmpty(item.optString("latitude")) ? "" : item.optString("latitude").trim();//纬度
                                String longitudes = TextUtils.isEmpty(item.optString("longitude")) ? "" : item.optString("longitude").trim();//经度
                                String businessLicence = TextUtils.isEmpty(item.optString("no")) ? "" : item.optString("no").trim();//经营执照
                                int operationsTatus = item.optInt("operationstatus");//操作状态(0：删除；icv1：新增；icv2：修改,-1正常)
                                int isDelete = item.optInt("isdelete");//是否删除（1：正常 0：删除）
                                long timeStamp = item.optLong("timestamp");//时间戳
                                MaketSubject ms = new MaketSubject();
                                ms.setMaketId(maketId);
                                ms.setAreaId(areaId);
                                ms.setMaketName(maketName);
                                ms.setOperator(operator);
                                ms.setTel(tel);
                                ms.setMaketAddress(maketAddress);
                                ms.setCategory(category);
                                ms.setMaketBy(maketBy);
                                ms.setCreateDate(createDate);
                                ms.setLatitudes(latitudes);
                                ms.setLongitudes(longitudes);
                                ms.setBusinessLicence(businessLicence);
                                ms.setOperationsTatus(operationsTatus);
                                ms.setIsDelete(isDelete);
                                ms.setTimeStamp(timeStamp);
                                updateMaketList.add(ms);
                            }
                            //从服务器获取数据完成，更新数据库
                            Message message = new Message();
                            message.what = UPDATE_SUCCESS;
                            handler.sendMessage(message);

                        } else {
                            if (isUpdateBaseData) {//基地有数据更新
                                Message message = new Message();
                                message.what = UPDATE_SUCCESS;
                                handler.sendMessage(message);
                            } else {//当前数据是最新的，无需更新。
                                Message message = new Message();
                                message.what = NOUPDATE;
                                handler.sendMessage(message);

                            }
                        }
                    }
                } catch (JSONException e) {
                    if (isUpdateBaseData) {
                        T.showShort(context, R.string.maket_data_error);
                        Message message = new Message();
                        message.what = UPDATE_SUCCESS;
                        handler.sendMessage(message);
                    } else {
                        Message message = new Message();
                        message.what = SERVICE_DATA_ERROR;
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_SUCCESS:
                    showDialog.dismissLoadDialog();
                    BaseBaseAndMaketDBUpdate.updateDB(updateBaseList, updateMaketList, context);
                    break;
                case UPDATE_FAIL:

                    break;
                case SERVICE_ERROR:
                    showDialog.dismissLoadDialog();
                    T.showShort(context, R.string.service_error);
                    break;
                case NOUPDATE:
                    showDialog.dismissLoadDialog();
                    T.showShort(context, R.string.no_update);
                    break;
                case SERVICE_DATA_ERROR:
                    showDialog.dismissLoadDialog();
                    T.showShort(context, R.string.service_data_error);
                    break;
            }
        }
    };
}
